package com.example.main.controller;


import com.example.base.entity.User;
import com.example.base.entity.UserCode;
import com.example.base.entity.UserInfo;
import com.example.base.exception.GlobalException;
import com.example.base.service.UserService;
import com.example.base.utils.Md5Generator;
import com.example.base.utils.MessageGenerator;
import com.example.base.utils.TokenUtils;
import com.example.base.vo.RespBean;
import com.example.base.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

//    @RequestMapping("getUser/{id}")
//    public String getUser(@PathVariable int id) {
//        return userService.sel(id).toString();
//    }

    @PostMapping("/login")
    @ResponseBody
    public RespBean login(User user) {
        if (userService.isLoginSuccess(user)) {
            user.setPassWord(Md5Generator.getMD5String(user.getPassWord()));
            User u = userService.getUserByEmail(user.getEmail());
            UserInfo info = u.getUserInfo();
            String userCode = userService.getUserCodeByUid(info.getId());
            String token = TokenUtils.getToken(user);
            return RespBean.success(respVal(user, token, info.getStudentNo(), userCode));
        } else {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
    }

    private Map<Object, Object> respVal(User user, String token, String studentNo, String code) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("info", user);
        map.put("token", token);
        map.put("studentNo", studentNo);
        map.put("verifyCode", code);
        return map;
    }
}